package raie.mapcomponent;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.ContentConnection;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.location.Coordinates;

import com.nokia.mid.ui.gestures.GestureEvent;
import com.nokia.mid.ui.gestures.GestureInteractiveZone;
import com.nokia.mid.ui.gestures.GestureListener;
import com.nokia.mid.ui.gestures.GestureRegistrationManager;

public class MapComponent extends Canvas implements GestureListener {

	private String mapUrl;
	private int zoom;
	private Coordinates coord;
	private Image zoomIn=null;
	private Image zoomOut=null;
	private GestureInteractiveZone zoomInTouch;
	private GestureInteractiveZone zoomOutTouch;
	private GestureInteractiveZone scrollTouch;
	
	public MapComponent(){
		super();
	}
	
	public MapComponent(Coordinates coordinate, int zoomlevel){
		super();
		init();
		this.coord = coordinate;
		this.zoom = zoomlevel;
		this.mapUrl = "http://m.ovi.me/?nord&z="+this.zoom+"&f=1&c="+this.coord.getLatitude()+","+this.coord.getLongitude();
	}
	

	public void init(){
		this.zoom = 10;
		try {
			zoomIn = Image.createImage("/zoomin.png");
			zoomOut = Image.createImage("/zoomout.png");
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		GestureRegistrationManager.setListener(this, this);
		zoomInTouch = new GestureInteractiveZone(GestureInteractiveZone.GESTURE_TAP);
		zoomOutTouch = new GestureInteractiveZone(GestureInteractiveZone.GESTURE_TAP);
		scrollTouch = new GestureInteractiveZone(GestureInteractiveZone.GESTURE_FLICK);

        zoomInTouch.setRectangle(190, 60, 64, 64); //whole screen
        zoomOutTouch.setRectangle(190, 110, 64, 64); //whole screen
        scrollTouch.setRectangle(0, 0, getWidth(), getHeight());
        GestureRegistrationManager.register(this, zoomInTouch);
        GestureRegistrationManager.register(this, zoomOutTouch);
        GestureRegistrationManager.register(this, scrollTouch);
	}
	
	protected void paint(Graphics g) {
		int pos = Graphics.TOP|Graphics.LEFT;
		g.fillRect(0, 0, getWidth(), getHeight());
		Image mapImage = null;
		try{
			mapImage = getImageRequest(this.mapUrl);
		}catch(Exception e){}
		g.drawImage(mapImage, 0, 0, pos);
		g.drawImage(zoomIn, 190, 60, pos);
		g.drawImage(zoomOut, 190, 110, pos);
	}

	public void gestureAction(Object container,GestureInteractiveZone gestureInteractiveZone,GestureEvent gestureEvent) {
		if(gestureInteractiveZone.equals(zoomInTouch)){
			if(gestureEvent.getType() == GestureInteractiveZone.GESTURE_TAP){
				this.zoom = this.zoom + 1;
				this.mapUrl = "http://m.ovi.me/?nord&z="+this.zoom+"&f=1&c="+this.coord.getLatitude()+","+this.coord.getLongitude();
				repaint();
				System.err.println("says");
			}
		}
		if(gestureInteractiveZone.equals(zoomOutTouch)){
			if(gestureEvent.getType() == GestureInteractiveZone.GESTURE_TAP){
				this.zoom--;
				this.mapUrl = "http://m.ovi.me/?nord&z="+this.zoom+"&f=1&c="+this.coord.getLatitude()+","+this.coord.getLongitude();
				repaint();
			}
		}
		if(gestureInteractiveZone.equals(scrollTouch)){
			if(gestureEvent.getType() == GestureInteractiveZone.GESTURE_FLICK){
				System.err.println(gestureEvent.getFlickSpeedX()+","+gestureEvent.getFlickSpeedY());
				if(gestureEvent.getFlickSpeedX() != 0){
					if(this.coord.getLatitude()>0){
						this.coord.setLatitude(this.coord.getLatitude() + 3.60/zoom);
					}else{
						this.coord.setLatitude(this.coord.getLatitude() - 3.60/zoom);
					}
				}
				if(gestureEvent.getFlickSpeedY() != 0){
					if(this.coord.getLongitude() > 0){
						this.coord.setLongitude(this.coord.getLongitude() + 0.360/zoom);
					}else{
						this.coord.setLongitude(this.coord.getLongitude() - 0.360/zoom);
					}
				}
				this.mapUrl = "http://m.ovi.me/?nord&z="+this.zoom+"&f=1&c="+this.coord.getLatitude()+","+this.coord.getLongitude();
				repaint();
			}
		}
	}
	
	//utility function
	public static Image getImageRequest(String urlstring){
		Image im = null;
	   	byte imageData[];
	   	ContentConnection conn = null;
		DataInputStream strim = null;
		ByteArrayOutputStream oStrim = null;
		System.out.println(urlstring);
	   	try{
				conn = (ContentConnection) Connector.open(urlstring);
				strim = conn.openDataInputStream();
				int length = (int) conn.getLength();
				if(!(conn.getType().equals("image/jpeg")||
						conn.getType().equals("image/png")||
						conn.getType().equals("image/gif")||
						conn.getType().equals("image/bmp"))){
					try {
						im = Image.createImage("/gambar/stub2.png");
					} catch (IOException e) {
					}
				}else{
					if (length != -1){
						imageData = new byte[length];
						try{
							strim.read(imageData);
						}catch(Exception e){
							e.printStackTrace();
						}
					} else { // Length not available...
						oStrim = new ByteArrayOutputStream();
						int ch;
						while ((ch = strim.read()) != -1){
							oStrim.write(ch);
						}
						imageData = oStrim.toByteArray();
					}
					im = Image.createImage(imageData, 0, imageData.length);
				}
	   	}catch (Exception e) {
		}finally{
			try { if(oStrim!= null)  oStrim.close(); } catch (IOException ignored) {}
			try { if(strim != null) strim.close();} catch (IOException ignored) {}
			try { if(conn != null) conn.close();} catch (IOException ignored) {}
		}
		
		return im;
	}

	//getter-setter
	public String getMapUrl(){
		return this.mapUrl;
	}
	public int getZoomLevel(){
		return this.zoom;
	}
	public Coordinates getCoordinates(){
		return this.coord;
	}
	public void setMapUrl(String mapUrl){
		this.mapUrl = mapUrl;
	}
	public void setZoomLevel(int zoomLevel){
		this.zoom = zoomLevel;
	}
	public void setCoordinates(Coordinates c){
		this.coord = c;
	}
}
